//
//  MTBLEManager.swift
//  Clock
//
//  Created by 方强 on 16/6/30.
//  Copyright © 2016年 MT. All rights reserved.
//

import UIKit
import CoreBluetooth

public class MTBLEManager: NSObject, CBCentralManagerDelegate{
    
    private static var mMTBLEManager:MTBLEManager?;
    
    public static let ENABLEBLE_CHANGE       = "ENABLEBLE_CHANGE";
    
    public static func getInstance() -> MTBLEManager?{
        if (mMTBLEManager == nil) {
            mMTBLEManager = MTBLEManager();
        }
        return mMTBLEManager;
    }
    
    private var manager: CBCentralManager!;
    private override init() {
        super.init();
        manager = CBCentralManager(delegate: self, queue: nil);
    }
    
    // 获取CBmanager
    public func getCBCentralManager() -> CBCentralManager!{
        return self.manager;
    }
    
    // 蓝牙状态改变
    public func centralManagerDidUpdateState(_ central: CBCentralManager){
        if #available(iOS 10.0, *) {
            if(central.state.rawValue == CBManagerState.poweredOn.rawValue){
                let nc = NotificationCenter.default;
                nc.post(name: NSNotification.Name(rawValue: MTBLEManager.ENABLEBLE_CHANGE), object: true);
                return;
            }
            if(central.state == CBManagerState.poweredOff){
                stopScan();
                let nc = NotificationCenter.default;
                nc.post(name: NSNotification.Name(rawValue: MTBLEManager.ENABLEBLE_CHANGE), object: false);
                return;
            }
        } else {
            if(central.state.rawValue == CBCentralManagerState.poweredOn.rawValue){
                let nc = NotificationCenter.default;
                nc.post(name: NSNotification.Name(rawValue: MTBLEManager.ENABLEBLE_CHANGE), object: true);
                return;
            }
            
            if(central.state.rawValue == CBCentralManagerState.poweredOff.rawValue){
                stopScan();
                let nc = NotificationCenter.default;
                nc.post(name: NSNotification.Name(rawValue: MTBLEManager.ENABLEBLE_CHANGE), object: false);
                return;
            }
        }
        
    }
    
    // 查看是否使能
    public func isEnable() -> Bool{
        if #available(iOS 10.0, *) {
            return (manager!.state.rawValue == CBManagerState.poweredOn.rawValue);
        } else {
            return (manager!.state.rawValue == CBCentralManagerState.poweredOn.rawValue);
        }
    }
    
    // 开始扫描
    private var scan_flag = false;
    private var serviceUuids: [CBUUID]?;
    private var scanCallback: MTBLEManager_ScanCallback!;
    private var worktime:Int = 5;
    private var sleeptime:Int = 1;
    private var scanTimes:Int = 1;
    private var scanLoop:Bool = false;   // 是否循环扫描
    public func startScan(scanmode:MTBLEManager_ScanMode, serviceUuids: [CBUUID]?, scanCallback: MTBLEManager_ScanCallback, worktime:Int, sleeptime:Int, scanTimes:Int) -> Bool{
       
        if((scan_flag) || (!isEnable())){  // 正在扫描，或者蓝牙未开启
            return false;
        }
        self.serviceUuids = serviceUuids;
        self.scanCallback = scanCallback;
        self.worktime = worktime;
        self.sleeptime = sleeptime;
        self.scanTimes = scanTimes;
        if(self.scanTimes == 0){  // 如果扫描次数设置成0的话，则是一直循环扫描
            scanLoop = true;
        }else{
            scanLoop = false;
        }
        
        self.scan_flag = true;
        
        startScanIsr();
        
        return true;
    }
    
    // 停止扫描
    public func stopScan() -> Bool{
        
        if(!scan_flag){
            return false;
        }
        
        scan_flag = false;
        
        manager?.stopScan();
        
        timer?.invalidate();
        
        return true;
    }
    
    // 扫描回调
    public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){
        if((RSSI.intValue <= -100) || (RSSI.intValue>0)){
            return;
        }
        // peripheral.identifier
        let device = MTBLEDevice(peripheral: peripheral, advertisementData: advertisementData, rssi: RSSI.intValue);

        scanCallback.onScan?(device);
        
    }
    
    // 开始扫描
    private var timer:Timer?;

    // 开启扫描定时器方法
    func startScanIsr(){
        if(!isEnable()){
            return;
        }
        if(!scan_flag){
            return;
        }
        if(!scanLoop){  // 不是无限循环扫描的情况
            scanTimes -= 1;
            if(scanTimes <= 0){
                scanCallback.onScanOver?(ErroCode.ERROMAP["OK"]!);
                return;
            }
        }
        
        MTTools.logout(log: "开始扫描");
        manager?.scanForPeripherals(withServices: self.serviceUuids, options: nil);
        
        timer = Timer.scheduledTimer(timeInterval: TimeInterval(self.worktime), target: self, selector: #selector(stopScanIsr), userInfo: nil, repeats: false);
    }
    
    // 挂你扫码定时方法
    func stopScanIsr(){
        MTTools.logout(log: "停止扫描");
        manager?.stopScan();
        timer = Timer.scheduledTimer(timeInterval: TimeInterval(self.sleeptime), target: self, selector: #selector(startScanIsr), userInfo: nil, repeats: false);
    }
    
    // 连接
    private var MTBLEManager_ConnectCallbackDir: Dictionary<CBPeripheral, MTBLEManager_ConnectCallback> = Dictionary<CBPeripheral, MTBLEManager_ConnectCallback>();
    public func connect(peripheral:CBPeripheral, callback:MTBLEManager_ConnectCallback!) -> ErroCode?{
        MTBLEManager_ConnectCallbackDir[peripheral] = callback;
        if(!isEnable()){
            return ErroCode.ERROMAP["bleunable"];
        }
        manager.connect(peripheral, options: nil);
        
        return ErroCode.ERROMAP["OK"];
    }
    
    // 断开连接
    public func disConect(peripheral:CBPeripheral) -> ErroCode?{
        
        manager.cancelPeripheralConnection(peripheral);
        
        return ErroCode.ERROMAP["OK"];
    }
    
    // 连接成功回调
    public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral){
        print("didConnectPeripheral");
        let callback = MTBLEManager_ConnectCallbackDir[peripheral];
        if(callback == nil){
            return;
        }
        if(callback?.onConnect != nil){
            callback?.onConnect!(peripheral, ErroCode.ERROMAP["OK"]);
        }
    }
    
    // 断开连接回调
    public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        print("didDisconnectPeripheral");
        let callback = MTBLEManager_ConnectCallbackDir[peripheral];
        if(callback == nil){
            return;
        }
        if(callback?.onDisConnect != nil){
            callback?.onDisConnect!(peripheral, ErroCode.ERROMAP["OK"]);
        }
    }
    
    
    // 连接失败回调
    public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        print("didFailToConnectPeripheral");
        let callback = MTBLEManager_ConnectCallbackDir[peripheral];
        if(callback == nil){
            return;
        }
        if(callback?.onConnect != nil){
            callback?.onConnect!(peripheral, ErroCode(code: ErroCode.CUSTOMCODE, msg: error.debugDescription));
        }
    }
}

public enum MTBLEManager_ScanMode {
    case LOWPOWER // 低功耗
    case BLANCE // 平衡模式
    case FAST // 快速扫描
}

public class MTBLEManager_ConnectCallback: NSObject{
    public override init() {
        super.init();
    }
    
    public var onConnect:((CBPeripheral, ErroCode?)->Void)?;
    public var onDisConnect:((CBPeripheral, ErroCode?)->Void)?;
}

// 扫描回调
public class MTBLEManager_ScanCallback: NSObject{
    public override init() {
        super.init();
    }
    
    public var onScan:((MTBLEDevice)->Void)?;
    public var onScanFail:((ErroCode)->Void)?;
    public var onScanOver:((ErroCode)->Void)?;
}


